import QtQuick 2.12
import QtQuick.Controls 2.5
import QtQuick.Window 2.12
import QtQuick.Layouts 1.12
import QtQuick.Dialogs 1.0
import AIClient.module 1.0

Page {

    signal createTrainjob(string train_dataset_id, string val_dataset_id, string model_id, string trainjob_name, string trainjob_description, string budget, string trainjob_param, string trainjob_version)
    //signal getTrainjob(string uid)
    signal cancel()
    signal error(string msg)

    signal viewDataset(string uid)
    signal viewModel(string uid)
    signal viewModelVersion(string uid, string verison)

//    AIClient {
//        id: client
//    }

//    TipMessage {
//        id: tip
//        width: parent.width
//    }

//    function setToken(token) {
//        m_token = token
//    }

//    property string m_token: ""
    property int m_mode: 1
    function setMode(mode) {
        m_mode = mode
    }

    property string m_uid: ""

    function setConfig(name, description, hour, gpu, param, version, train_dataset_index, val_dataset_index, model_index, mversion)
    {
        trainjob_name.text = name
        trainjob_description.text = description
        trainjob_hour.text = hour
        trainjob_gpu.text = gpu
        trainjob_param.text = param
        trainjob_version.text = version
        trainDatasetCombo.currentIndex = train_dataset_index
        valDatasetCombo.currentIndex = val_dataset_index
        modelCombo.currentIndex = model_index
        model_version.text = mversion

    }

    function updateMode() {
        if ( m_mode === 1 )
        {
            trainjob_name.text = ""
            trainjob_description.text = ""
            trainjob_hour.text = ""
            trainjob_gpu.text = ""
            trainjob_param.text = ""
            trainjob_version.text = ""
            trainDatasetCombo.currentIndex = -1
            valDatasetCombo.currentIndex = -1
            modelCombo.currentIndex = -1

            trainjob_name.enabled = true
            trainjob_description.enabled = true
            trainjob_hour.enabled = true
            trainjob_gpu.enabled = true
            trainjob_param.enabled = true
            trainjob_version.enabled = true
            trainDatasetCombo.enabled = true
            valDatasetCombo.enabled = true
            modelCombo.enabled = true
            m_uid = ""
            btn.text = "创建"
            btn.enabled = true
            model_version.enabled = false
            model_version.visible = false
            model_version_tip.visible = false
            btn_model_version.visible = false
        }
        else
        {
            trainjob_name.enabled = false
            trainjob_description.enabled = false
            trainjob_hour.enabled = false
            trainjob_gpu.enabled = false
            trainjob_param.enabled = false
            trainjob_version.enabled = false
            trainDatasetCombo.enabled = false
            valDatasetCombo.enabled = false
            modelCombo.enabled = false
            btn.text = "关闭"
            btn.enabled = false
            model_version.enabled = false
            model_version.visible = true
            model_version_tip.visible = true
            btn_model_version.visible = true
//            client.setConfig(m_token)
//            var res = client.get_trainjob(m_uid)
//            var jres = JSON.parse(res)
//            if ( jres["code"] === 0 )
//            {


//                trainjob_name.text = jres["data"]["name"]
//                trainjob_description.text = jres["data"]["description"]
//                var budget = JSON.parse(jres["data"]["budget"])
//                trainjob_hour.text = budget["HOURS"]
//                trainjob_gpu.text = budget["GPU"]
//                trainjob_param.text = jres["data"]["train_args"]
//                trainjob_version.text = jres["data"]["version"]

//                btn.text = "关闭"
//            }

        }
    }

//    property string m_trainjob_name: ""
//    property string m_trainjob_budget: ""
//    property string m_trainjob_description: ""
//    property int m_trainjob_version: 0
//    property  name: value

    id: trainjob_create
    title: "创建训练任务"
    visible: false
    //visibility: "Maximized"
//    modality: Qt.ApplicationModal
//    minimumWidth: Screen.desktopAvailableWidth*0.3
//    maximumWidth: Screen.desktopAvailableWidth
//    minimumHeight: Screen.desktopAvailableHeight*0.75
//    maximumHeight: Screen.desktopAvailableHeight
    width: Screen.desktopAvailableWidth*0.5
    height: Screen.desktopAvailableHeight*0.75
//    color: "azure"

//    Component.onCompleted: {
//        updateModel()
//        updateDataset()
//    }

    function updateDataset() {
        removeAllDatasetItem()
        client.setConfig(m_token)
        var res = client.list_dataset()
        var jres = JSON.parse(res)
        if ( jres["code"] !== 0 )
        {
            tip.showmsg(jres["message"])
            return
        }
        //tip.showmsg("获取数据集成功")
        var data = jres["data"]
        for ( var i=0; i<data.length ; i++ )
        {
            data[i]["uid"] = data[i]["id"]
            data[i]["create_date"] = data[i]["create_date"]//.substring(0,19).replace(/T/," ")
            data[i]["text"] = data[i]["name"]
            data[i]["color"] = "black"
            addDatasetItem(jres["data"][i])
        }
    }

    function addDatasetItem(item) {
        datasetModel.append(item)
    }

    function removeAllDatasetItem() {
        datasetModel.clear()
    }

    function removeDatasetItem(item) {
        datasetModel.remove(item)
    }

    ListModel {
        /* 数据项 */
        id: datasetModel
        ListElement {
            uid: "uuid";
            name: "red";
            create_date: "2020";
            text: "t";
            color: "black";
        }
    }

    function updateModel() {
        removeModelAll()
        client.setConfig(m_token)
        var res = client.list_model_available()
        var jres = JSON.parse(res)
        if ( jres["code"] !== 0 )
        {
            tip.showmsg(jres["message"])
            return
        }
        //tip.showmsg("获取模型成功")
        var data = jres["data"]
        for ( var i=0; i<data.length ; i++ )
        {
            data[i]["uid"] = data[i]["id"]
            data[i]["text"] = data[i]["name"]
            data[i]["create_date"] = data[i]["create_date"]//.substring(0,19).replace(/T/," ")
            data[i]["color"] = "black"
            addModelItem(jres["data"][i])
        }
    }

    function addModelItem(item) {
        myModel.append(item)
    }

    function removeModelAll() {
        myModel.clear()
    }

    function removeModelItem(item) {
        myModel.remove(item)
    }

    ListModel {
        /* 数据项 */
        id: myModel
        ListElement {
            uid: "uuid";
            name: "red";
            model_class: "test";
            dependencies: "denpend";
            create_date: "2020";
            text: "t";
            color: "black";
        }
        //ListElement { uid: "uuid"; name: "blue"; model_class: "test";dependencies: "denpend";create_date: "2020";}
        //ListElement { uid: "uuid"; name: "green"; model_class: "test";dependencies: "denpend";create_date: "2020";}
    }

    Rectangle{
        anchors.fill: parent
        color:"azure"
        width: trainjob_create.width
        height: trainjob_create.height


    GridLayout {
//            ScrollBar.vertical: ScrollBar {
//                id: scrollBar
//                parent: flickable.parent
//                anchors.top: flickable.top
//                anchors.left: flickable.right
//                anchors.bottom: flickable.bottom
//            }

        id: grid_trainjob_create
        rows:12
        columns: 3
        anchors.topMargin: 50
        anchors.bottomMargin: 50
        anchors.leftMargin: 50
        anchors.rightMargin: 50
        anchors.fill: parent
        columnSpacing: 5
        rowSpacing: 15
        Text {
            text: qsTr("名称")
            font.pointSize: 12
            font.bold: false
            Layout.preferredHeight: 50
            Layout.maximumHeight: 60
            Layout.preferredWidth: 180
            //Layout.fillWidth: true
            color: "black"
            Layout.column: 0
            Layout.row: 0
        }
        TextField {
            id: trainjob_name
            text: ""
            selectByMouse: true
            font.pointSize: 12
            Layout.minimumHeight: 12*2
            Layout.preferredHeight: 50
            Layout.preferredWidth: 500
            Layout.maximumHeight: 60
            Layout.fillWidth: true
            Layout.row: 0
            Layout.column: 1
        }
        Text {
            text: qsTr("版本")
            font.pointSize: 12
            font.bold: false
            Layout.preferredHeight: 50
            Layout.maximumHeight: 60
            //Layout.fillWidth: true
            color: "black"
            Layout.column: 0
            Layout.row: 1
        }
        TextField {
            id: trainjob_version
            text: ""
            selectByMouse: true
            font.pointSize: 12
            Layout.minimumHeight: 12*2
            Layout.preferredHeight: 50
            Layout.preferredWidth: 500
            Layout.maximumHeight: 60
            Layout.fillWidth: true
            Layout.row: 1
            Layout.column: 1
        }
        Text {
            text: qsTr("训练数据集")
            font.pointSize: 12
            font.bold: false
            Layout.preferredHeight: 50
            Layout.maximumHeight: 60
            //Layout.fillWidth: true
            color: "black"
            Layout.column: 0
            Layout.row: 2
        }
        ComboBox {
            id: trainDatasetCombo
            currentIndex: -1
            Layout.column: 1
            Layout.row: 2
            font.pointSize: 12
            Layout.minimumHeight: 12*3
            Layout.preferredHeight: 50
            Layout.preferredWidth: 500
            Layout.maximumHeight: 60
            Layout.fillWidth: true
            model: datasetModel
            textRole: "text"
        }
        OrangeButton {
            id: btn_trainDataset
            text: "查看数据集"
//            Layout.columnSpan: 2
            Layout.minimumHeight: 25
            Layout.maximumHeight: 60
            Layout.minimumWidth: 180
            Layout.column: 2
            Layout.row: 2
            enabled: trainDatasetCombo.currentIndex>=0
        //Layout.preferredWidth: 500
            onClicked: {
                var dataset_index = trainDatasetCombo.currentIndex
                viewDataset(datasetModel.get(dataset_index).uid)
            }
        }

        Text {
            text: qsTr("验证数据集")
            font.pointSize: 12
            font.bold: false
            Layout.preferredHeight: 50
            Layout.maximumHeight: 60
            //Layout.fillWidth: true
            color: "black"
            Layout.column: 0
            Layout.row: 3
        }
        ComboBox {
            id: valDatasetCombo
            currentIndex: -1
            Layout.column: 1
            Layout.row: 3
            font.pointSize: 12
            Layout.minimumHeight: 12*3
            Layout.preferredHeight: 50
            Layout.preferredWidth: 500
            Layout.maximumHeight: 60
            Layout.fillWidth: true
            model: datasetModel
            textRole: "text"
        }
        OrangeButton {
            id: btn_valDataset
            text: "查看数据集"
//            Layout.columnSpan: 2
            Layout.minimumHeight: 25
            Layout.maximumHeight: 60
            Layout.minimumWidth: 180
            Layout.column: 2
            Layout.row: 3
        //Layout.preferredWidth: 500
            enabled: valDatasetCombo.currentIndex>=0

            onClicked: {
                var dataset_index = valDatasetCombo.currentIndex
                viewDataset(datasetModel.get(dataset_index).uid)
            }
        }
        Text {
            text: qsTr("模型")
            font.pointSize: 12
            font.bold: false
            Layout.preferredHeight: 50
            Layout.maximumHeight: 60
            //Layout.fillWidth: true
            color: "black"
            Layout.column: 0
            Layout.row: 4
        }
        ComboBox {
            id: modelCombo
            currentIndex: -1
            Layout.column: 1
            Layout.row: 4
            font.pointSize: 12
            Layout.minimumHeight: 12*3
            Layout.preferredHeight: 50
            Layout.preferredWidth: 500
            Layout.maximumHeight: 60
            Layout.fillWidth: true
            model: myModel
            textRole: "text"
        }
        OrangeButton {
            id: btn_model
            text: "查看"
//            Layout.columnSpan: 2
            Layout.minimumHeight: 25
            Layout.maximumHeight: 60
            Layout.minimumWidth: 180
            Layout.column: 2
            Layout.row: 4
        //Layout.preferredWidth: 500
            enabled: modelCombo.currentIndex>=0

            onClicked: {
                var model_index = modelCombo.currentIndex
                viewModel(myModel.get(model_index).uid)
            }
        }
        Text {
            id: model_version_tip
            text: qsTr("模型版本")
            font.pointSize: 12
            Layout.preferredHeight: 50
            Layout.maximumHeight: 60
            //Layout.fillWidth: true
            Layout.row: 5
            Layout.column: 0
            color: "black"
        }
        TextField {
            id: model_version
            text: ""
            selectByMouse: true
            font.pointSize: 12
            Layout.minimumHeight: 12*2
            Layout.preferredHeight: 50
            Layout.preferredWidth: 500
            Layout.maximumHeight: 60
            Layout.fillWidth: true
            Layout.row: 5
            Layout.column: 1
        }
        OrangeButton {
            id: btn_model_version
            text: "查看"
//            Layout.columnSpan: 2
            Layout.minimumHeight: 25
            Layout.maximumHeight: 60
            Layout.minimumWidth: 180
            Layout.column: 2
            Layout.row: 5
        //Layout.preferredWidth: 500
            enabled: model_version.text != ""

            onClicked: {
                var model_index = modelCombo.currentIndex
                viewModelVersion(myModel.get(model_index).uid, model_version.text)
            }
        }
        Text {
            text: qsTr("训练参数")
            font.pointSize: 12
            Layout.preferredHeight: 50
            Layout.maximumHeight: 60
            //Layout.fillWidth: true
            Layout.row: 6
            Layout.column: 0
            color: "black"
        }
        ScrollTextView {
            Layout.preferredHeight: 200
            Layout.minimumHeight: 12*5
            Layout.maximumHeight: 300
            //height: 500
            //Layout.fillHeight: true
            Layout.fillWidth: true
            Layout.row: 6
            Layout.column: 1
            id: trainjob_param
        }
//        ScrollView{
//            //Layout.minimumWidth: 500
//            Layout.maximumHeight: 300
//            Layout.minimumHeight: 12*5
//            Layout.preferredHeight: 200
//            Layout.fillWidth: true
//            Layout.row: 5
//            Layout.column: 1
//            TextArea {
//                id: trainjob_param
//                text: ""
//                selectByMouse: true
//                font.pointSize: 12

//                background: Rectangle{
//                    anchors.fill: parent
//                    width: 500
//                    color: "white"
//                    border.color: "gray"
//                }
//            }
//        }
        Text {
            text: qsTr("最长训练时间(h)")
            font.pointSize: 12
            Layout.preferredHeight: 50
            Layout.maximumHeight: 60
            //Layout.fillWidth: true
            Layout.row: 7
            Layout.column: 0
            color: "black"
        }
        TextField {
            id: trainjob_hour
            text: ""
            selectByMouse: true
            font.pointSize: 12
            Layout.minimumHeight: 12*2
            Layout.preferredHeight: 50
            Layout.preferredWidth: 500
            Layout.maximumHeight: 60
            Layout.fillWidth: true
            Layout.row: 7
            Layout.column: 1
        }
        Text {
            text: qsTr("GPU个数")
            font.pointSize: 12
            Layout.preferredHeight: 50
            Layout.maximumHeight: 60
            //Layout.fillWidth: true
            Layout.row: 8
            Layout.column: 0
            color: "black"
        }
        TextField {
            id: trainjob_gpu
            text: ""
            selectByMouse: true
            font.pointSize: 12
            Layout.minimumHeight: 12*2
            Layout.preferredHeight: 50
            Layout.preferredWidth: 500
            Layout.maximumHeight: 60
            Layout.fillWidth: true
            Layout.row: 8
            Layout.column: 1
        }
//        ScrollView{
//            //Layout.minimumWidth: 500
//            Layout.fillHeight: true
//            Layout.minimumHeight: 12*5
//            Layout.preferredHeight: 200
//            Layout.fillWidth: true
//            Layout.row: 6
//            Layout.column: 1
//            TextArea {
//                id: trainjob_budget
//                text: ""
//                selectByMouse: true
//                font.pointSize: 12

//                background: Rectangle{
//                    anchors.fill: parent
//                    width: 500
//                    color: "white"
//                }
//            }
//        }
        Text {
            text: qsTr("训练任务描述")
            font.pointSize: 12
            Layout.preferredHeight: 50
            Layout.maximumHeight: 300
            //Layout.fillWidth: true
            Layout.row: 9
            Layout.column: 0
            color: "black"
        }
        ScrollTextView {
            Layout.preferredHeight: 200
            Layout.minimumHeight: 12*5
            Layout.maximumHeight: 300
            //height: 500
            //Layout.fillHeight: true
            Layout.fillWidth: true
            Layout.row: 9
            Layout.column: 1
            id: trainjob_description
        }
//        ScrollView{
//            //Layout.minimumWidth: 500
//            Layout.maximumHeight: 300
//            Layout.minimumHeight: 12*5
//            Layout.preferredHeight: 200
//            Layout.fillWidth: true
//            Layout.row: 8
//            Layout.column: 1
//            TextArea {
//                id: trainjob_description
//                text: ""
//                selectByMouse: true
//                font.pointSize: 12

//                background: Rectangle{
//                    anchors.fill: parent
//                    width: 500
//                    color: "white"
//                    border.color: "gray"
//                }
//            }
//        }
//            TextField {
//                id: dataset_description
//                text: m_dataset_description
//    //            passwordCharacter: "*"
//                Layout.preferredHeight: 200
//                Layout.preferredWidth: 500
//                Layout.fillHeight: true
//                Layout.fillWidth: true
//                Layout.row: 1
//                Layout.column: 1
//            }


//        Rectangle{
//            Layout.preferredHeight: 40
//            Layout.fillHeight: true
//            Layout.row: 9
//            Layout.column: 0
//        }
        RowLayout {
            Layout.row: 10
            Layout.column: 1
            Button {
                id: btn
                text: "确定"
//            Layout.columnSpan: 2
                Layout.minimumHeight: 25
                Layout.maximumHeight: 60
                Layout.minimumWidth: 180
            //Layout.preferredWidth: 500

                background: Rectangle {
                    anchors.fill: parent
                    color: "gold"
                    border.color: "black"
                    border.width: parent.hovered?0:2
                    radius: 5
                }
                onClicked: {
                    //client.setConfig(m_token)
                    if ( m_mode === 1 )
                    {
                        var model_index = modelCombo.currentIndex
                        if ( model_index < 0 )
                        {
                            error("请选择模型！")
                            return
                        }
                        var train_dataset_index = trainDatasetCombo.currentIndex
                        if ( train_dataset_index < 0 )
                        {
                            error("请选择训练数据集！")
                            return
                        }
                        var val_dataset_index = valDatasetCombo.currentIndex
                        if ( val_dataset_index < 0 )
                        {
                            error("请选择验证数据集！")
                            return
                        }
                        if ( trainjob_name.text.length <= 0 )
                        {
                            error("请输入训练任务名称！")
                            return
                        }
                        if ( trainjob_description.text.length <= 0 )
                        {
                            error("请输入训练任务描述！")
                            return
                        }
                        if ( trainjob_param.text.length <= 0 )
                        {
                            error("请输入训练任务参数！")
                            return
                        }
                        if ( !isRealNum(trainjob_hour.text) )
                        {
                            error("请输入正确的时长！")
                            return
                        }
                        if ( !isRealNum(trainjob_gpu.text) )
                        {
                            error("请输入正确的gpu个数！")
                            return
                        }
                        if ( !isRealNum(trainjob_version.text) )
                        {
                            error("请输入正确的版本号！")
                            return
                        }
                        var jbudget = {}
                        jbudget["GPU_COUNT"] = Number(trainjob_gpu.text)
                        jbudget["HOURS"] = Number(trainjob_hour.text)
                        var budget= JSON.stringify(jbudget)
                        createTrainjob(datasetModel.get(train_dataset_index).uid, datasetModel.get(val_dataset_index).uid, myModel.get(model_index).uid, trainjob_name.text, trainjob_description.text, budget, trainjob_param.text, trainjob_version.text)
                        return

                    }

                }
            }
            Button {
                text: "返回"
//            Layout.columnSpan: 2
                Layout.maximumHeight: 60
                Layout.minimumWidth: 180
            //Layout.preferredWidth: 500
                Layout.minimumHeight: 12*1.5
                background: Rectangle {
                    anchors.fill: parent
                    color: "gold"
                    border.color: "black"
                    border.width: parent.hovered?0:2
                    radius: 5
                }
                onClicked: {
                    cancel()
                }
            }
            Rectangle {

    //                Layout.minimumHeight: 200
                Layout.maximumHeight: 60
                Layout.fillHeight: true
                Layout.fillWidth: true
                color: "transparent"
                Layout.columnSpan: 3
            }
        }
        Rectangle {
            Layout.row: 11
            Layout.column: 0
//                Layout.minimumHeight: 200
            Layout.fillHeight: true
            Layout.fillWidth: true
            color: "transparent"
            Layout.columnSpan: 3
        }

//        TextEdit {
//            id: content
//            text: m_content
//            width: 350
//            Layout.preferredHeight: 500
//        }
       }
    }
    function isRealNum(val){
        // isNaN()函数 把空串 空格 以及NUll 按照0来处理 所以先去除，

      if(val === "" || val === null){
            return false;
      }
       if(!isNaN(val)){
      //对于空数组和只有一个数值成员的数组或全是数字组成的字符串，isNaN返回false，例如：'123'、[]、[2]、['123'],isNaN返回false,
       //所以如果不需要val包含这些特殊情况，则这个判断改写为if(!isNaN(val) && typeof val === 'number' )
        return true;
      }

     else{
        return false;
      }
    }
    signal success()
}
